import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  Radio,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
} from 'antd';
const RadioGroup = Radio.Group;
const RadioButton = Radio.Button;

import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import { enquireScreen, unenquireScreen } from 'enquire-js';

import styles from './TableList.less';

Date.prototype.Format = function (fmt) { //author: meizz
  var o = {
    "Y+": this.getUTCFullYear(),
    "M+": this.getMonth() + 1, //月份
    "D+": this.getDate(), //日
    "H+": this.getHours(), //小时
    "m+": this.getMinutes(), //分
    "s+": this.getSeconds(), //秒
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
    "S": this.getMilliseconds() //毫秒
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
  if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
}

const FormItem = Form.Item;
const { Option } = Select;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');
const statusMap = ['default', 'success'];
const status = ['未使用', '已使用'];
const mstatus = ['未用', '已用'];

const CreateForm = Form.create()(props => {
  const { modalVisible, form,article, handleAdd,accounts, handleModalVisible } = props;
  const okHandle = () => {
   
    form.validateFields((err, fieldsValue) => {
      if (fieldsValue.title.length < 5 || fieldsValue.title.length > 30){
          message.warn('标题长度应在5-30之间,当前:'+fieldsValue.title.length,1)
          return
      }
      if (err) return;
      form.resetFields();
      fieldsValue.article_url = article.url
      handleAdd(article,fieldsValue);
    });
  };

  const praseType = value => {
    switch(value){
      case 'BAIJIA':
        return "百家"
      case 'TOUTIAO':
        return "头条"
      case 'QIER':
        return "企鹅"
      case 'DAYU':
        return "大鱼"

    }
  }
 
  var listAccountsOption = () => {
    var res = [];
    for(var key in accounts){
      res.push(<Option key={key} value={accounts[key].id} >{praseType(accounts[key].plat)}-{accounts[key].nick_name}</Option>)
    }
    return res
  }

  var catsArray = {
    "娱乐":  "娱乐",
    "情感":  "情感",
    "社会":  "社会",
    "美食":  "美食",
    "国际":  "国际",
    "体育": "体育",
    "动漫":  "动漫",
		"财经":  "财经",
		"互联网": "互联网",
		"科技":  "科技",
		"汽车":  "汽车",
		"教育":  "教育",
		"时尚":  "时尚",
		"游戏":  "游戏",
		"旅游":  "旅游",
		"生活":  "生活",
		"创意":  "创意",
		"搞笑":  "搞笑",
		"美图":  "美图",
		"女人":  "女人",
		"家居":  "家居",
		"健康":  "健康",
		"两性":  "两性",
		"育儿":  "育儿",
		"文化":  "文化",
		"宠物":  "宠物",
		"科学":  "科学",
		"电影":  "电影",
  }

  var listOption = () => {
    var res = [];
    for(var key in catsArray){
      res.push(<Option key={key} value={key} >{key}</Option>)
    }
    return res
  }

  var handleChange = (e) => {
    // this.setState({ type: e.target.value });
  }


  return (
    <Modal
      title={article == undefined?"发布:":"发布:"+article.title}
      
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible(false)}
    >
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="分类">
        {form.getFieldDecorator('title',{
          rules: [{ required: true }],
          initialValue: article == undefined?"":article.title,
        })
        ( <Input />)}
      </FormItem>

       <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="账号">
        {form.getFieldDecorator('account_id',{
          rules: [{ required: true }],
        })
        ( <Select style={{ width: 180 }} onChange={this.handleChange}>
          {listAccountsOption()}
        </Select>)}
      </FormItem>

      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="分类">
        {form.getFieldDecorator('article_cat',{
          rules: [{ required: true }],
          initialValue: "娱乐",
        })
        ( <Select style={{ width: 120 }} onChange={this.handleChange}>
          {listOption()}
      </Select>)}
      </FormItem>

         <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="类型"
          label="类型"
        >
          {form.getFieldDecorator('type',{
          rules: [{ required: true }],
          initialValue: "ARTICLE",
        })(
            <RadioGroup onchange={this.handleChange}>
              <RadioButton value="ARTICLE">文章</RadioButton>
              <RadioButton value="GALLERY">图集</RadioButton>
              <RadioButton value="VIDEO">视频</RadioButton> 
            </RadioGroup>
          )}
        </FormItem>
    </Modal>
  );
});


let isMobile;
enquireScreen(b => {
  isMobile = b;
});

@connect(({ rule, loading }) => ({
  rule,
  loading: loading.models.rule,
}))
@Form.create()
export default class SearchList extends PureComponent {
  state = {
    updateArticle:{},
    modalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    word:"",
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'rule/fetchPubAccounts',
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      page: pagination.current,
      size: pagination.pageSize,
      word: this.state.word,
    };

    dispatch({
      type: 'rule/search',
      payload: params,
    });
  };


  refresh = () => {
    const { dispatch } = this.props;
    const { rule: { searchData:{ page,page_size }}} = this.props;

    dispatch({
      type: 'rule/search',
      payload: {
        page:page,
        size:page_size,
        word:this.state.word,
      },
    });
  }

  handleSearch = e => {
    console.log("handleSearch",e)
    const { dispatch } = this.props;
    const { rule: { searchData:{ page,page_size }}} = this.props;

    this.state.word = e
      dispatch({
        type: 'rule/search',
        payload: {
          page:page,
          size:page_size,
          word:this.state.word,
        },
      });
  }

  renderForm() {
    return this.state.expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  handleUpdateVisible = (flag,article) => {
    this.setState({
      updateArticle:article,
      modalVisible: !!flag,
    });
  }

  publish = (article,field) =>{
    this.useArticle(article)
    this.props.dispatch({
      type: 'rule/addTask',
      payload: field,
    })
     this.handleUpdateVisible(false)
  }

  useArticle = article => {
    this.props.dispatch({
      type: 'rule/updatePubStatus',
      payload: {
        article_id: article.article_id,
        status: article.status > 0? 0:1,
      },
      callback: () => {
        message.success('标记修改成功');
        this.refresh()
      }
    })
  }
  
  praseType = value => {
    switch(value){
      case 'kb_news_bagua':
        return "娱乐"
      case 'kb_news_sports':
        return "运动"
      case 'kb_news_laugh':
        return "搞笑"
      case 'kb_news_hotnews':
        return "热文"
      case 'kb_news_sex':
        return '情感'
      case 'kb_news_tech':
        return '教育'
      case 'kb_news_chaobao':
        return '时尚'
      case 'kb_news_car':
        return '汽车'
      case 'kb_news_beauty':
        return '美女'
      case 'kb_news_nba':
        return 'nba'
      case 'kb_news_college':
        return '大鱼'
      case 'kb_news_pet':
        return '宠物'
      case 'kb_news_health':
        return '健康'
      case 'kb_news_movie':
        return '电影'
      case 'kb_news_baby':
        return '育儿'
      case 'kb_news_gaojidi':
        return '数码'
      case 'kb_news_cate':
        return '美食'
    }
  }
  
  praseDate = value => {
    var date = new Date(value)
    date.setHours(date.getHours()-8)
    var s = date.Format('YYYY-MM-DD HH:mm:ss')
    return s
  }
  render() {
    // praseType = this.praseType
    const { rule: { searchData,pubAccounts }, loading } = this.props;
    const { selectedRows, modalVisible,updateArticle } = this.state;

    var columns = []
    if (isMobile){
      columns = [
        {
          title: '标题',
          dataIndex: 'url',
          render: (val,record) => <a href={record.url} target="_Blank">{record.title}</a>,
        },
        {
          title: '分类',
          width: 50,
          dataIndex: 'type',
          render: val => <span>{this.praseType(val)}</span>,
        },
        {
          title: '状态',
          width: 60,
          dataIndex: 'status',
          render(val) {
            return <Badge status={statusMap[val]} text={mstatus[val]} />;
          },
        },
        {
          title: '时间',
          width: 55,
          dataIndex: 'create_time',
          render: val => <span>{this.praseDate(val).substring(3,14)}</span>,
        },
        {
          title: '操作',  
          render: (val , record) => (
            <span>
              <a onClick={()=> this.useArticle(record)}>{record.status?'取消':'使用'}</a>
              <Divider style={{margin:5,marginLeft:0}} type='horizontal'/>
              <a onClick={()=> this.handleUpdateVisible(true,record)}>发布</a>
            </span>
          ),
        },
      ];
    }else{
      columns = [
        {
          title: '编号',
          dataIndex: 'article_id',
        },
        {
          title: '标题',
          dataIndex: 'url',
          width: 500,
          render: (val,record) => <a href={record.url} target="_Blank">{record.title}</a>,
        },
        {
          title: '分类',
          dataIndex: 'type',
          render: val => <span>{this.praseType(val)}</span>,
        },
        {
          title: '状态',
          dataIndex: 'status',
          filters: [
            {
              text: status[0],
              value: 0,
            },
            {
              text: status[1],
              value: 1,
            }
          ],
          onFilter: (value, record) => record.status.toString() === value,
          render(val) {
            return <Badge status={statusMap[val]} text={status[val]} />;
          },
        },
        {
          title: '抓取时间',
          dataIndex: 'create_time',
          sorter: true,
          render: val => <span>{this.praseDate(val)}</span>,
        },
        {
          title: '操作',  
          render: (val , record) => (
            <span>
              <a onClick={()=> this.useArticle(record)}>{record.status?'取消':'使用'}</a>
              <Divider type='vertical'/>
              <a onClick={()=> this.handleUpdateVisible(true,record)}>发布</a>
            </span>
          ),
        },
      ];
    }

    const parentMethods = {
      handleAdd: this.publish,
      handleModalVisible: this.handleUpdateVisible,
      article: updateArticle,
      accounts:pubAccounts,
    };

    return (
      <div style={{ margin: '0 -46px 0' }}>
        <Card bordered={false}>
          <div className={styles.tableList}>
          <div style={{ textAlign: 'center' }}>
            <Input.Search
              placeholder="请输入"
              enterButton="搜索"
              size="large"
              onSearch={this.handleSearch}
              style={{ width: 522 }}
            />
            </div>
            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={searchData}
              columns={columns}
              pagination={true}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        <CreateForm {...parentMethods} modalVisible={modalVisible} />
      </div>
    );
  }
}
